﻿using CinemaMaestro.ViewModels;
using CinemaMaestro.WindowsApplication.EndPoints;
using MetroFramework;
using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CinemaMaestro.WindowsApplication.Actor
{
    public partial class ActorsForm : MetroForm
    {
       private ActorEndPoints endPoints;
       private List<ActorViewModel> actors = new List<ActorViewModel>();
       private byte[] picture;

       public ActorsForm(HttpClient client)
        {
            this.endPoints = new ActorEndPoints(client);
            InitializeComponent();
            PopulateActorsListView(); 

            deleteButton.Enabled = false;
            updateButton.Enabled = false;
        }    

        private void clearButton_Click(object sender, EventArgs e)
        {
            lastNameTextBox.Text = String.Empty;
            firstNameTextBox.Text = String.Empty;
            birthDayDateTime.Text = String.Empty;
            actorsListView.SelectedIndices.Clear();
            deleteButton.Enabled = false;
            updateButton.Enabled = false;
            createButton.Enabled = true;
            picture = null;
            pictureBox.Image = null;
        }

        private async void PopulateActorsListView()
        {
            actorsListView.Items.Clear();
            try
            {
                actors = await endPoints.GetAllActorsAsync();
                foreach (var actor in actors)
                {
                    var item = new ListViewItem();
                    item.Text = actor.Id.ToString();
                    item.SubItems.Add(actor.FirstName);
                    item.SubItems.Add(actor.LastName);
                    item.SubItems.Add(actor.BirthDay.ToShortDateString());
                    actorsListView.Items.Add(item);
                }
            }
            catch
            {
                MetroMessageBox.Show(this, "Cannot retrieve actors!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }           
        }

        private void actorsListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (actorsListView.SelectedItems.Count == 1)
            {
                deleteButton.Enabled = true;
                updateButton.Enabled = true;
                createButton.Enabled = false;
                picture = null;
                pictureBox.Image = null;
                firstNameTextBox.Text = actorsListView.SelectedItems[0].SubItems[1].Text;
                lastNameTextBox.Text = actorsListView.SelectedItems[0].SubItems[2].Text;
                birthDayDateTime.Text = actorsListView.SelectedItems[0].SubItems[3].Text;
                int id = Int32.Parse(actorsListView.SelectedItems[0].SubItems[0].Text);
                picture = actors.First(x => x.Id == id).Image;
                UpdatePictureBox();
            }
        }

        private void ActorsForm_MouseDown(object sender, MouseEventArgs e)
        {
            actorsListView.SelectedIndices.Clear();
            deleteButton.Enabled = false;
            updateButton.Enabled = false;
            createButton.Enabled = true;
            firstNameTextBox.Text = String.Empty;
            lastNameTextBox.Text = String.Empty;
            birthDayDateTime.Text = String.Empty;
            picture = null;
            pictureBox.Image = null;
        }

        private async void deleteButton_Click(object sender, EventArgs e)
        {
            deleteButton.Enabled = false;
            updateButton.Enabled = false;
            try
            {
                int selectedId = Int32.Parse(actorsListView.SelectedItems[0].SubItems[0].Text);
                await endPoints.DeleteActorAsync(selectedId);
            }
            catch
            {
                MetroMessageBox.Show(this, "Cannot delete actor!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            finally
            {
                PopulateActorsListView();
                actorsListView.SelectedIndices.Clear();
                firstNameTextBox.Text = String.Empty;
                lastNameTextBox.Text = String.Empty;
                birthDayDateTime.Text = String.Empty;
                picture = null;
                pictureBox.Image = null;
                createButton.Enabled = true;
            }
        }

        private void browseButton_Click(object sender, EventArgs e)
        {
            if (pictureDialog.ShowDialog() == DialogResult.OK)
            {
                string filename = pictureDialog.FileName;
                picture = File.ReadAllBytes(filename);
                UpdatePictureBox();
            }
        }

        private void UpdatePictureBox()
        {
            Bitmap image;
            using (MemoryStream stream = new MemoryStream(picture))
            {
                image = new Bitmap(stream);
            }
            pictureBox.Image = image;
        }

        private async void createButton_Click(object sender, EventArgs e)
        {
            if (ValidateActor())
            {
                try
                {
                    var actor = new ActorViewModel
                    {
                        FirstName = firstNameTextBox.Text,
                        LastName = lastNameTextBox.Text,
                        BirthDay = birthDayDateTime.Value,
                        Image = picture
                    };
                    await endPoints.CreateActorAsync(actor);
                }
                catch
                {
                    MetroMessageBox.Show(this, "Cannot create actor!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                finally
                {
                    PopulateActorsListView();
                    firstNameTextBox.Text = String.Empty;
                    lastNameTextBox.Text = String.Empty;
                    birthDayDateTime.Text = String.Empty;
                    picture = null;
                    pictureBox.Image = null;
                }    
            }                      
        }

        private bool ValidateActor()
        {
            if (firstNameTextBox.Text == String.Empty)
            {
                MetroMessageBox.Show(this, "Please provide a first name for the Actor!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            if (lastNameTextBox.Text == String.Empty)
            {
                MetroMessageBox.Show(this, "Please provide a last name for the Actor!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            if (picture == null)
            {
                MetroMessageBox.Show(this, "Please select a picture for the Actor!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            return true;
        }

        private async void updateButton_Click(object sender, EventArgs e)
        {
            deleteButton.Enabled = false;
            updateButton.Enabled = false;
            if (ValidateActor())
            {
                try
                {
                    int selectedId = Int32.Parse(actorsListView.SelectedItems[0].SubItems[0].Text);
                    var actor = new ActorViewModel
                    {
                        Id = selectedId,
                        FirstName = firstNameTextBox.Text,
                        LastName = lastNameTextBox.Text,
                        BirthDay = birthDayDateTime.Value,
                        Image = picture
                    };
                    await endPoints.UpdateActorAsync(actor);
                }
                catch
                {
                    MetroMessageBox.Show(this, "Cannot update actor!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                finally
                {
                    PopulateActorsListView();
                    actorsListView.SelectedIndices.Clear();
                    firstNameTextBox.Text = String.Empty;
                    lastNameTextBox.Text = String.Empty;
                    birthDayDateTime.Text = String.Empty;
                    picture = null;
                    pictureBox.Image = null;
                    createButton.Enabled = true;
                } 
            }
        }
    }
}
